package com.taylor.community.controller.advice;

import com.taylor.community.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//表示只去扫描代有Controller注解的bean
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
    @ExceptionHandler({Exception.class})
    public void handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.error("服务器发生异常："+e.getMessage());
        //异常信息存储在栈中 将其中的信息遍历出来
        for (StackTraceElement element : e.getStackTrace()){
            logger.error(element.toString());
        }
        //判断请求是普通请求 or 异步请求 因为两者返回的东西不一样
        String xRequestedWith = request.getHeader("x-requested-with");
        //异步请求
        if("XMLHttpRequest".equals(xRequestedWith)){
            //返回普通格式的字符串 前端手动转换成JSON格式
            response.setContentType("application/plain;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(CommunityUtil.getJSONString(1,"服务器异常!"));
        }
        else{
            //普通请求则重定向到错误页面
            response.sendRedirect(request.getContextPath() + "/error");
        }
    }

}
